import React, { useState, useCallback, useMemo } from "react";
import InputAtom from "../../Atoms/Input.Atom";
import { InputAtomEnum } from "../../Atoms/Input.Atom/enum";
import ImageAtom from "../../Atoms/Image.Atom";
import ImageEnum from "../../Atoms/Image.Atom/enum";
import SearchIcon from "../../../shared/icons/search.svg?react";
import CloseIcon from "../../../shared/icons/close.svg?react";
import { SearchModuleProps } from "./type";

const SearchModule: React.FC<SearchModuleProps> = (props) => {
  const { placeholder, value, setSearchQuery } = props;
  const [initialSearch, setInitialSearch] = useState(false);

  const handleSearchChange = useCallback(
    (value: string) => {
      setSearchQuery(value);
      setInitialSearch(value.length > 0);
    },
    [setSearchQuery]
  );

  const clearSearch = useCallback(() => {
    setSearchQuery("");
    setInitialSearch(false);
  }, [setSearchQuery]);

  useMemo(() => setSearchQuery, [setSearchQuery]);

  return (
    <div className="rounded-lg border-[2px] border-borderColor bg-borderColor flex items-center">
      <ImageAtom
        type={ImageEnum.enum_defaultSvg}
        icon={<SearchIcon />}
        className="h-6 w-6 stroke-tiffany flex m-2"
      />
      <InputAtom
        placeholder={placeholder}
        type={InputAtomEnum.TEXT_ONLY}
        className="bg-transparent border-[0px]"
        onChange={handleSearchChange}
        value={value}
      />
      {initialSearch && (
        <ImageAtom
          onClick={(event) => {
            event.stopPropagation();
            clearSearch();
          }}
          type={ImageEnum.enum_defaultSvg}
          icon={<CloseIcon />}
          className="h-4 w-4 fill-tiffany flex m-2 cursor-pointer"
        />
      )}
    </div>
  );
};

export default React.memo(SearchModule);
